package com.jcl.core.db;

import com.jcl.core.db.model.InitDataSourceModel;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * @ClassName DbServerTools
 * @Author yyliu
 * @Date 2018/12/14 10:07
 * @Version 1.0
 **/
public class DbServerTools {

    private String dbServerSql;

    private String dbCorpSql;

    public static final String DB_SERVER_SQL = "select * from t_console_db_server ";

    public static final String DB_CORP_SQL = "select * from t_console_db_corp ";


    public DbServerTools() {

    }

    public DbServerTools(String dbServerSql, String dbCorpSql) {
        this.dbServerSql = dbServerSql;
        this.dbCorpSql = dbCorpSql;
    }

    public InitDataSourceModel getInitDataSourceModel(DataSource consoleDataSource) {
        InitDataSourceModel model = InitDataSourceModel.newInstance();
        DbServer server = new DbServer(consoleDataSource);
        List<Map<String, Object>> dbServerList = server.query(getDbServerSql());
        List<Map<String, Object>> dbCorpList = server.query(getDbCorpSql());
        // 关闭连接
        server.closeConnection();
        model.setDbServerList(dbServerList);
        model.setDbCorpList(dbCorpList);
        return model;
    }

    public String getDbServerSql() {
        if (null == dbServerSql) {
            dbServerSql = DB_SERVER_SQL;
        }
        return dbServerSql;
    }

    public void setDbServerSql(String dbServerSql) {
        this.dbServerSql = dbServerSql;
    }

    public String getDbCorpSql() {
        if (null == dbCorpSql) {
            dbCorpSql = DB_CORP_SQL;
        }
        return dbCorpSql;
    }

    public void setDbCorpSql(String dbCorpSql) {
        this.dbCorpSql = dbCorpSql;
    }

    public static class DbServer {

        private DbConnection connection = null;

        public DbServer() {
        }

        public DbServer(DataSource dataSource) {
            try {
                connection = new DbConnection(dataSource.getConnection());
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        public List<Map<String, Object>> query(String sql) {
            return connection.query(sql);
        }

        public int insert(String sql) {
            return connection.insert(sql);
        }

        public int update(String sql) {
            return connection.update(sql);
        }

        public int delete(String sql) {

            return connection.delete(sql);
        }

        public void closeConnection() {
            connection.closeConnection();
        }
    }
}
